import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
	state: () => ({
		loginForm: null,
		token: null,
		userInfo: null
	}),
	actions: {
		/**
     * 用户登录操作
     * @param loginForm
     */
    async loginAction (loginForm: any) {
      const { msg: token } = await requestLogin(loginForm)
      // 记住密码
      if (loginForm.isRemember) {
        // 密码加密
        loginForm.password = useCrypto.encrypt(loginForm.password, 'user')
        this.loginForm = loginForm
      } else { // 不记住密码
        this.loginForm = {
          account: '',
          password: '',
          isRemember: false
        }
      }
			this.setToken(token)
      // 获取用户信息
      await this.getUserInfoAction()
			// 跳转首页
      uni.switchTab({
      	url: "/pages/tabBar/index/index"
      })
    },
		// 设置/存储token
		setToken(token = '') {
			this.token = token
		},
    /**
     * 获取用户信息
     */
    async getUserInfoAction () {
      const { data: userInfo } = await requestUserInfo()
      this.userInfo = userInfo
    },
    /**
     * 退出登录操作
     */
    async logoutAction () {
      const { msg } = await requestLogout()
      if (!msg) {
				uni.showToast({
					title: '退出成功'
				});
			}
			// 清空用户缓存
      useUserStore().$reset()
			// 跳转登录页
			setTimeout(() => {
				uni.reLaunch({
					url: "/pages/login/login"
				})
			}, 1000)
    }
	},
	persist: {
		key: 'user',
		paths: ['loginForm', 'token', 'userInfo']
	}
})